<template>
    <div class="app-container">
        <div class="list-box">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                     label-width="68px">
                <el-form-item label="表名称" prop="tableName">
                    <el-input
                            v-model="queryParams.tableName"
                            placeholder="请输入表名称"
                            clearable
                            @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item label="表描述" prop="tableComment">
                    <el-input
                            v-model="queryParams.tableComment"
                            placeholder="请输入表描述"
                            clearable
                            @keyup.enter.native="handleQuery"/>
                </el-form-item>
                <el-form-item>
                    <el-button color="#DBA5FF" icon="Search" size="small" @click="handleQuery">搜索</el-button>
                    <el-button color="#DBA5FF" icon="Refresh" size="small" @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <router-link to="/home">
                        <el-button icon="Monitor" size="small" color="#FBA5FF">首页</el-button>
                    </router-link>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="success" plain icon="Download" size="small"
                               @click="openImportTable">导入
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="primary" plain icon="Upload" size="small" :disabled="multiple"
                               @click="handleGenTable">生成
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="info" plain icon="Edit" size="small" :disabled="single"
                               @click="handleEditTable">修改
                    </el-button>
                </el-col>
                <el-col :span="1.5">
                    <el-button type="danger" plain icon="Delete" size="small" :disabled="multiple"
                               @click="handleDelete">删除
                    </el-button>
                </el-col>
                <right-toolbar style="position:absolute;right: 30px;bottom: 5px" v-model:showSearch="showSearch"
                               @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange"
                      :default-sort="{ prop: 'createTime', order: 'descending' }"
                      height="calc(100vh - 140px)"
                      style="border-radius: 15px;box-shadow: 0 0 15px 3px rgba(0,0,0,0.5);">
                <el-table-column type="selection" align="center" width="30px"></el-table-column>
                <el-table-column label="序号" type="index" width="50px" align="center">
                    <template #default="scope">
                        <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="表名称" align="center" prop="tableName" sortable
                                 :show-overflow-tooltip="true" min-width="20%"/>
                <el-table-column label="实体" align="center" prop="className"
                                 :show-overflow-tooltip="true" min-width="20%"/>
                <el-table-column label="表描述" align="center" prop="tableComment"
                                 :show-overflow-tooltip="true" min-width="20%"/>
                <el-table-column label="创建时间" align="center" prop="createTime" width="160px" sortable/>
                <el-table-column label="更新时间" align="center" prop="updateTime" width="160px" sortable/>
                <el-table-column label="操作" align="center" width="260px"
                                 class-name="small-padding fixed-width">
                    <template #default="scope">
                        <el-button style="margin-left: 1px;width: 50px" color="#EB95FF" size="small" icon="View"
                                   @click="handlePreview(scope.row)" plain>预览
                        </el-button>
                        <el-button style="margin-left: 1px;width: 50px" type="info" size="small" icon="Edit"
                                   @click="handleEditTable(scope.row)" plain>编辑
                        </el-button>
                        <el-button style="margin-left: 1px;width: 50px" type="danger" size="small" icon="Delete"
                                   @click="handleDelete(scope.row)" plain>删除
                        </el-button>
                        <el-button style="margin-left: 1px;width: 50px" type="success" size="small" icon="Refresh"
                                   @click="handleSynchDb(scope.row)" plain>同步
                        </el-button>
                        <el-button style="margin-left: 1px;width: 50px" type="primary" size="small" icon="Download"
                                   @click="handleGenTable(scope.row)" plain>生成
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
                        v-model:limit="queryParams.pageSize"
                        @pagination="getList" style="position: absolute; left: 10px;bottom: 5px"/>
            <div class="icon-help-box" style="left: auto;right: 10px;">
                <el-tooltip effect="light" placement="top-start"
                            content="去gitee获取源码和代码框架">
                    <a href="https://gitee.com/v-function/generate" target="_blank">
                        <img src="@/assets/icons/gitee.svg" alt="github"/>
                    </a>
                </el-tooltip>
                <el-tooltip effect="light" placement="top-start"
                            content="如何连接本站项目数据库？请发送邮箱至2873585297@qq.com">
                    <a href="https://mail.qq.com/" target="_blank">
                        <el-icon size="30px" color="#f88141">
                            <InfoFilled/>
                        </el-icon>
                    </a>
                </el-tooltip>
                <el-tooltip effect="light" placement="top-start">
                    <a href="https://agree.vhans.cloud/" target="_blank">
                        <el-icon size="30px">
                            <img src="@/assets/icons/agree.svg" alt="agree"/>
                        </el-icon>
                    </a>
                    <template #content>
                        <a href="https://agree.vhans.cloud/" target="_blank">
                            <p style="margin: 0;">推荐一个我开发的校园信息发布与交友网站，快来看看吧！</p>
                            <img src="/images/agree.png" alt="agree"
                                 style="width: 380px;height: 200px;object-fit: contain;"/>
                        </a>
                    </template>
                </el-tooltip>
            </div>
        </div>
        <!-- 预览界面 -->
        <el-dialog :title="preview.title" v-model="preview.open" width="80%" top="5vh" append-to-body
                   style="border-radius: 20px;" center>
            <el-tabs v-model="preview.activeName" @tab-change="copyStatus = '点击复制'">
                <el-tab-pane
                        v-for="(value, key) in preview.data"
                        :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
                        :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
                        :key="key">
                    <div style="position:relative;background: bisque; border-radius: 10px;">
                        <pre style="padding: 5px 10px;font-size: 16px;"><code
                                v-html="highlightedCode(value, key)"></code></pre>
                        <el-button style="position:absolute;top: 5px;right:5px;width: 75px;opacity: 0.8;"
                                   color="#EBA5FF" size="small" icon="DocumentCopy" @click="handleCopy(value)">
                            {{ copyStatus }}
                        </el-button>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
        <import-table ref="import" @ok="handleQuery"/>
    </div>
</template>

<script>
import {delTable, genCode, listTable, previewTable, synchDb} from "@/api/gen.js";
import importTable from "./importTable";
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
import {messageConfirm, notifySuccess} from "@/utils/modal.ts";
import router from "@/router/index.ts";
import java from "highlight.js/lib/languages/java";
import xml from "highlight.js/lib/languages/xml";
import sql from "highlight.js/lib/languages/sql";
import javascript from "highlight.js/lib/languages/javascript";
import typescript from "highlight.js/lib/languages/typescript";
import SvgIcon from "@/components/SvgIcon/index.vue";

hljs.registerLanguage("java", java);
hljs.registerLanguage("xml", xml);
hljs.registerLanguage("html", xml);
hljs.registerLanguage("vue", xml);
hljs.registerLanguage("javascript", javascript);
hljs.registerLanguage("typescript", typescript);
hljs.registerLanguage("sql", sql);

export default {
    name: "Gen",
    components: {SvgIcon, importTable},
    data() {
        return {
            // 遮罩层
            loading: true,
            // 唯一标识符
            uniqueId: "",
            // 选中数组
            ids: [],
            // 选中表数组
            tableNames: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表数据
            tableList: [],
            // 日期范围
            dateRange: "",
            //复制状态
            copyStatus: "点击复制",
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                tableName: undefined,
                tableComment: undefined
            },
            // 预览参数
            preview: {
                open: false,
                title: "代码预览",
                data: {},
                activeName: "domain.java"
            }
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 查询表集合 */
        getList() {
            this.loading = true;
            listTable(this.queryParams).then(response => {
                    this.tableList = response.data.rows;
                    this.total = response.data.total;
                    this.loading = false;
                }
            );
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 生成代码操作 */
        handleGenTable(row) {
            const names = row.tableName || this.tableNames;
            if (names === "" || names.length === 0) {
                messageConfirm("请选择要生成的数据");
                return;
            }
            if (row.genType === "1") {
                genCode(row.tableName).then(res => {
                    notifySuccess("成功生成到路径：" + res.data.data);
                });
            } else {
                this.download.zip("/gen/batchGenCode?tables=" + names, "gen");
            }
        },
        /** 同步数据库操作 */
        handleSynchDb(row) {
            const tableName = row.tableName;
            messageConfirm('确认要强制同步"' + tableName + '"表结构吗？').then(function () {
                return synchDb(tableName);
            }).then(() => {
                notifySuccess("同步成功");
            }).catch(() => {
            });
        },
        /** 打开导入表弹窗 */
        openImportTable() {
            this.$refs.import.show();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 预览按钮 */
        handlePreview(row) {
            previewTable(row.tableId).then(response => {
                this.preview.data = response.data.data;
                this.preview.open = true;
                this.preview.activeName = "domain.java";
            });
        },
        /** 高亮显示 */
        highlightedCode(code, key) {
            const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
            let language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
            const result = hljs.highlight(language, code || "", true, null);
            return result.value || '&nbsp;';
        },
        /** 复制代码 */
        handleCopy(v) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(v).then(() => {
                    this.copyStatus = "复制成功";
                }).catch((e) => {
                    console.error('复制失败:', e);
                    this.copyStatus = "复制失败";
                })
            } else {
                this.execCommandCopyFallback(v);
            }
        },
        execCommandCopyFallback(text) {
            const textArea = document.createElement("textarea");
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            try {
                document.execCommand("copy");
                this.copyStatus = "复制成功";
            } catch (err) {
                console.error('execCommand 复制失败:', err);
                this.copyStatus = "复制失败";
            }
            document.body.removeChild(textArea);
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.tableId);
            this.tableNames = selection.map(item => item.tableName);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleEditTable(row) {
            const tableId = row.tableId || this.ids[0];
            return router.push({path: '/gen-edit/' + tableId});
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const tableIds = row.tableId || this.ids;
            messageConfirm('是否确认删除表编号为"' + tableIds + '"的数据项？').then(function () {
                return delTable(tableIds);
            }).then(() => {
                this.getList();
                notifySuccess("删除成功");
            }).catch(() => {
            });
        }
    }
};
</script>